<template>
  <view class="user-detail-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <view class="title">用户信息</view>
    </view>

    <!-- 用户基本信息 -->
    <view class="user-info" v-if="userInfo">
      <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
      <view class="user-meta">
        <text class="nickname">{{userInfo.nickname}}</text>
        <text class="bio">{{userInfo.bio || '这个人很懒，什么都没写~'}}</text>
      </view>
      <view class="user-stats">
        <view class="stat-item" @click="switchTab('travel')">
          <text class="stat-value">{{userInfo.travelCount || 0}}</text>
          <text class="stat-label">游记</text>
        </view>
        <view class="stat-item" @click="switchTab('like')">
          <text class="stat-value">{{userInfo.receivedLikes || 0}}</text>
          <text class="stat-label">点赞</text>
        </view>
        <view class="stat-item" @click="switchTab('favorite')">
          <text class="stat-value">{{userInfo.receivedFavorites || 0}}</text>
          <text class="stat-label">收藏</text>
        </view>
      </view>
    </view>

    <!-- 标签页 -->
    <view class="tabs-container">
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'travel'}" 
        @click="switchTab('travel')"
      >
        <text>游记</text>
      </view>
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'like'}" 
        @click="switchTab('like')"
      >
        <text>点赞</text>
      </view>
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'favorite'}" 
        @click="switchTab('favorite')"
      >
        <text>收藏</text>
      </view>
    </view>

    <!-- 游记列表 -->
    <view class="travel-list" v-if="travels.length > 0">
      <view class="travel-item" v-for="travel in travels" :key="travel.id" @click="goToTravelDetail(travel.id)">
        <view class="travel-images">
          <view class="image-grid" :class="getImageGridClass(travel.image)">
            <image v-for="(url, imgIndex) in travel.image.split(',')" 
                   :key="imgIndex" 
                   :src="url" 
                   mode="aspectFill"
                   @click.stop="previewImages(travel.image, imgIndex)">
            </image>
          </view>
        </view>
        <view class="travel-info">
          <text class="travel-content">{{travel.content}}</text>
          <view class="travel-stats">
            <view class="stat-item">
              <text class="iconfont icon-liulanliang"></text>
              <text class="stat-value">{{travel.views || 0}}</text>
            </view>
            <view class="stat-item" :class="{'active': travel.isLiked}">
              <text class="iconfont icon-icon"></text>
              <text class="stat-value">{{travel.likes || 0}}</text>
            </view>
            <view class="stat-item" :class="{'active': travel.isFavorited}">
              <text class="iconfont icon-shoucang"></text>
              <text class="stat-value">{{travel.favorites || 0}}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 无游记提示 -->
    <view class="no-travels" v-else-if="!loading && !travelLoading">
      <text class="no-travels-text">
        {{
          activeTab === 'travel' ? '暂无游记' : 
          activeTab === 'like' ? '暂无点赞的游记' : '暂无收藏的游记'
        }}
      </text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && !userInfo" class="loading-state">
      <view class="loading-content">
        <text class="loading-icon">🔄</text>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-if="error" class="error-state">
      <view class="error-content">
        <text class="error-icon">⚠️</text>
        <text class="error-text">{{error}}</text>
        <view class="retry-btn" @click="fetchUserInfo">重试</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getUserProfile, getUserInfo } from '@/api/user'
import { getTravelList, getUserTravelList, getLikedTravelList, getFavoritedTravelList } from '@/api/travel'

// 响应式数据
const userInfo = ref(null)
const travels = ref([])
const loading = ref(false)
const error = ref('')
const currentUser = ref(null)
const currentPage = ref(0)
const pageSize = ref(9999)
const hasMore = ref(true)
const userId = ref(null)
const travelLoading = ref(false)
const activeTab = ref('travel') // 当前激活的标签：travel, like, favorite

// 计算属性
const isCurrentUser = computed(() => {
  if (!currentUser.value || !userInfo.value) return false
  return currentUser.value.id === userInfo.value.id
})

// 获取路由参数
const getRouteParams = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage.options || {}
}

// 初始化用户信息
const initUserInfo = () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      currentUser.value = userInfo
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  if (!userId.value) return
  
  loading.value = true
  error.value = ''
  
  try {
    let res;
    if (currentUser.value && currentUser.value.id === userId.value) {
      // 如果是当前用户，使用 getUserProfile
      res = await getUserProfile()
    } else {
      // 如果是其他用户，使用 getUserInfo
      res = await getUserInfo(userId.value)
    }
    
    if (res.code === 200) {
      userInfo.value = res.data
    } else {
      throw new Error(res.message || '获取用户信息失败')
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    error.value = err.message || '加载失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 切换标签
const switchTab = (tab) => {
  if (activeTab.value === tab) return
  
  activeTab.value = tab
  // 重置分页
  currentPage.value = 0
  travels.value = []
  hasMore.value = true
  
  // 加载对应标签的数据
  fetchTravels()
}

// 获取游记列表
const fetchTravels = async (isLoadMore = false) => {
  if (!userId.value || travelLoading.value) return
  
  travelLoading.value = true
  try {
    const params = {
      page: isLoadMore ? currentPage.value : 0,
      size: pageSize.value,
      userId: userId.value
    }
    
    let res;
    
    // 根据当前标签获取不同的游记列表
    switch(activeTab.value) {
      case 'travel':
        res = await getUserTravelList(userId.value, params)
        break
      case 'like':
        res = await getLikedTravelList(params)
        break
      case 'favorite':
        res = await getFavoritedTravelList(params)
        break
    }
    
    if (res.code === 200) {
      const newTravels = res.data.content
      if (isLoadMore) {
        travels.value = [...travels.value, ...newTravels]
      } else {
        travels.value = newTravels
      }
      
      // 更新分页信息
      hasMore.value = !res.data.last
      currentPage.value = res.data.number + 1
      
      // 如果还有更多游记且不在加载中，自动加载更多
      if (hasMore.value && !travelLoading.value) {
        setTimeout(() => {
          fetchTravels(true)
        }, 500)
      }
    }
  } catch (err) {
    console.error('获取游记列表失败:', err)
    uni.showToast({
      title: '获取游记列表失败',
      icon: 'none'
    })
  } finally {
    travelLoading.value = false
  }
}

// 跳转到游记详情
const goToTravelDetail = (travelId) => {
  uni.navigateTo({
    url: `/pages/discovery/travel-detail?id=${travelId}`
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || travelLoading.value) return
  fetchTravels(true)
}

// 监听 hasMore 和 travelLoading 变化，自动加载更多
watch([hasMore, travelLoading], ([newHasMore, newLoading]) => {
  if (newHasMore && !newLoading && travels.value.length > 0) {
    fetchTravels(true)
  }
})

// 监听标签变化
watch(activeTab, () => {
  // 标签变化时重新加载数据
  currentPage.value = 0
  travels.value = []
  hasMore.value = true
  fetchTravels()
})

// 预览图片
const previewImages = (imageStr, currentIndex) => {
  const urls = imageStr.split(',')
  uni.previewImage({
    urls,
    current: currentIndex
  })
}

// 获取图片网格的类名
const getImageGridClass = (imageStr) => {
  const count = imageStr.split(',').length
  if (count === 1) return 'single'
  if (count === 2) return 'double'
  if (count === 3) return 'triple'
  if (count === 4) return 'quad'
  return 'multi'
}

// 页面加载时获取数据
onMounted(() => {
  initUserInfo()
  const params = getRouteParams()
  if (params.id) {
    userId.value = params.id
    fetchUserInfo()
    fetchTravels()
  }
})
</script>

<style lang="scss" scoped>
.user-detail-page {
  min-height: 100vh;
  background-color: #f8f9fa;

  .nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 90rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 100;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);

    .left {
      padding: 15rpx;
      margin-left: -15rpx;
      
      .iconfont {
        font-size: 36rpx;
        color: #333;
      }
    }

    .title {
      flex: 1;
      text-align: center;
      font-size: 34rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .user-info {
    margin-top: 90rpx;
    background-color: #fff;
    padding: 40rpx 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    .user-meta {
      text-align: center;
      margin-bottom: 30rpx;
      
      .nickname {
        display: block;
        font-size: 36rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .bio {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
      }
    }
    
    .user-stats {
      display: flex;
      justify-content: space-around;
      width: 100%;
      margin-bottom: 30rpx;
      
      .stat-item {
        text-align: center;
        
        .stat-value {
          display: block;
          font-size: 36rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 6rpx;
        }
        
        .stat-label {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  .tabs-container {
    display: flex;
    background-color: #fff;
    height: 80rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .tab-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      
      text {
        font-size: 28rpx;
        color: #666;
      }
      
      &.active {
        text {
          color: #42b983;
          font-weight: 500;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60rpx;
          height: 4rpx;
          background-color: #42b983;
          border-radius: 2rpx;
        }
      }
    }
  }

  .travel-list {
    padding: 20rpx;
    
    .travel-item {
      background: #fff;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      
      .travel-images {
        width: 100%;
        
        .image-grid {
          display: grid;
          gap: 6rpx;
          
          &.single {
            grid-template-columns: 1fr;
            
            image {
              height: 400rpx;
            }
          }
          
          &.double {
            grid-template-columns: repeat(2, 1fr);
            
            image {
              height: 300rpx;
            }
          }
          
          &.triple {
            grid-template-columns: repeat(3, 1fr);
            
            image {
              height: 240rpx;
            }
          }
          
          &.quad {
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(2, 1fr);
            
            image {
              height: 240rpx;
            }
          }
          
          &.multi {
            grid-template-columns: repeat(3, 1fr);
            
            image {
              height: 200rpx;
            }
          }
          
          image {
            width: 100%;
            object-fit: cover;
          }
        }
      }
      
      .travel-info {
        padding: 20rpx;
        
        .travel-content {
          font-size: 28rpx;
          color: #333;
          line-height: 1.6;
          margin-bottom: 16rpx;
        }
        
        .travel-stats {
          display: flex;
          align-items: center;
          
          .stat-item {
            display: flex;
            align-items: center;
            margin-right: 30rpx;
            
            &.active {
              color: #42b983;
            }
            
            .iconfont {
              font-size: 32rpx;
              margin-right: 8rpx;
            }
            
            .stat-value {
              font-size: 24rpx;
              color: #666;
            }
          }
        }
      }
    }
  }

  .load-more {
    text-align: center;
    padding: 20rpx;
    
    .load-more-text {
      font-size: 28rpx;
      color: #666;
    }
  }

  .no-travels {
    text-align: center;
    padding: 40rpx;
    
    .no-travels-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .loading-state, .error-state {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .loading-content, .error-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .loading-icon, .error-icon {
        font-size: 48rpx;
        margin-bottom: 16rpx;
      }
      
      .loading-text, .error-text {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 24rpx;
      }
      
      .retry-btn {
        background-color: #42b983;
        color: #fff;
        font-size: 28rpx;
        padding: 12rpx 30rpx;
        border-radius: 30rpx;
      }
    }
  }
}
</style> 